import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { getBanners, getHotRecommends, getNewAlbums, getRankings, getArtists } from "../api"
import type { Banner, HotRecommendItme, Album, ArtistData } from "../api/type"
interface RecommendState {
	banners: Banner[]
	hotRecommends: HotRecommendItme[]
	newAlbums: Album[]
	rankings: any[]
	artists: ArtistData[]
}

const initialState: RecommendState = {
	banners: [],
	hotRecommends: [],
	newAlbums: [],
	rankings: [],
	artists: [],
}

// 获取轮播图列表异步action
export const fetchBannersAction = createAsyncThunk("banners", async (args, { dispatch }) => {
	try {
		const res = await getBanners()
		dispatch(upadateBannersAction(res.banners))
	} catch (error) {
		console.log(error)
	}
})

// 获取热门推荐歌曲action
export const fetchHotRecommendsAction = createAsyncThunk("hotRecommends", async (args, { dispatch }) => {
	try {
		const res = await getHotRecommends(8)
		dispatch(updateHotRecommendsAction(res.result))
	} catch (error) {
		console.log(error)
	}
})

// 获取新碟列表action
export const fetchNewAlbumsAction = createAsyncThunk("newAlbums", async (args, { dispatch }) => {
	try {
		const res = await getNewAlbums(10)
		dispatch(updateNewAlbumsAction(res.albums))
	} catch (error) {
		console.log(error)
	}
})

// 获取榜单数据action
export const fetchRankingsAction = createAsyncThunk("rankings", async (args, { dispatch }) => {
	const rankingIds = [19723756, 3779629, 2884035]
	const promises: Promise<any>[] = rankingIds.map((id: number) => getRankings(id))
	const res = await Promise.all(promises)
	const rankings = res.map((item) => item.playlist)
	console.log(rankings)
	dispatch(updateRankingsAction(rankings))
})

// 获取歌手列表
export const fetchArtistsAction = createAsyncThunk("artists", async (args, { dispatch }) => {
	try {
		const res = await getArtists(5)
		dispatch(updateArtistsAction(res.artists))
	} catch (error) {
		console.log(error)
	}
})
const recommendSlice = createSlice({
	name: "recommend",
	initialState,
	reducers: {
		upadateBannersAction: (state, { payload }) => {
			state.banners = payload
		},
		updateHotRecommendsAction: (state, { payload }) => {
			state.hotRecommends = payload
		},
		updateNewAlbumsAction: (state, { payload }) => {
			state.newAlbums = payload
		},
		updateRankingsAction: (state, { payload }) => {
			state.rankings = payload
		},
		updateArtistsAction: (state, { payload }) => {
			state.artists = payload
		},
	},
})

export const {
	upadateBannersAction,
	updateHotRecommendsAction,
	updateNewAlbumsAction,
	updateRankingsAction,
	updateArtistsAction,
} = recommendSlice.actions
export default recommendSlice.reducer
